package com.example.redis.controller.lock;

import com.example.redis.view.lock.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/7/24 21:28
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
@RestController
@RequestMapping("/lock")
@Slf4j
public class LockController {

    final RedissonClient redissonClient;
    final RedisTemplate<String, String> stringRedisTemplate;

    @Autowired
    public LockController(RedissonClient redissonClient,
                          @Qualifier("stringRedisTemplate") RedisTemplate stringRedisTemplate) {
        this.redissonClient = redissonClient;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @GetMapping("")
    public Result test() {
        RLock lock = redissonClient.getLock("product-count");
        if (lock.tryLock()) {
            String count = stringRedisTemplate.opsForValue().get("count");
            if (StringUtils.isBlank(count) ||Long.valueOf(count) <=0) {
                this.unLockSafety(lock);
                log.error("售光");
                return Result.error("售光");
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Long countLong = stringRedisTemplate.opsForValue().decrement("count");
            log.info("countLong now is :{}",countLong);
            this.unLockSafety(lock);
            return Result.OK(countLong);
        } else {
            log.error("未争夺到锁");
            return Result.error("未争夺到锁");
        }

    }


    private void unLockSafety(RLock lock) {
        if (lock.isHeldByCurrentThread()) {
            lock.unlockAsync();
        }
    }

}
